import {
  computed,
  CSSProperties,
  defineComponent,
  ref,
  useTemplateRef,
  VNode,
} from 'vue';
import { Table, TableProps } from 'ant-design-vue';
import { number, oneOf, oneOfType } from 'vue-types';

export default defineComponent({
  name: 'Table',
  props: {
    height: oneOfType([number(), oneOf(['auto'] as const)]),
  },
  setup(props, { attrs }) {
    const tableRef = ref();

    const tableBodyHeight = ref(0);
    const onTableUpdated = ({ el }: VNode) => {
      const tableHeight = el?.querySelector('.ant-table-thead');
      const headerHeight = tableHeight?.clientHeight || 0;
      tableBodyHeight.value = el?.clientHeight - headerHeight;
    };

    const _tableProps = computed<TableProps>(() => {
      const scroll: TableProps['scroll'] = {
        x: 500,
      };
      const style: CSSProperties = {};
      if (props.height === 'auto') {
        return {
          scroll,
        };
      } else if (typeof props.height === 'number') {
        scroll.y = props.height;
        style['--bo-table-height'] = props.height;
      } else {
        scroll.y = tableBodyHeight.value;
        style['--bo-table-height'] = tableBodyHeight.value;
      }

      return {
        scroll,
        style,
      };
    });

    return (
      <div>
        <Table ref={tableRef} {...attrs} onVnodeUpdated={onTableUpdated} />
      </div>
    );
  },
});
